/*
这里考到了递归
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <glob.h>

#define PATHSIZE 1024

static int64_t mydu(const char * path);
static int path_noloop(const char * path);

int main(int argc, char * argv[])
{
	//参数检验
	if(argc < 2)
	{
		printf("err\n");
		exit(1);
	}
	//打印
	printf("main:%ld\n", mydu(argv[1]) / 2);

	exit(0);
}

static int64_t mydu(const char * path)
{
	static struct stat statres;
	static char nextpath[PATHSIZE];
	glob_t globres;
	int i;
	int64_t sum;

	/*获取文件或目录的信息*/
	if(lstat(path, &statres) < 0)
	{
		perror("lstat");
		exit(1);
	}

	/*如果是普通文件*/
	if(!S_ISDIR(statres.st_mode))
	{
		return statres.st_blocks;
	}

	/*如果是目录*/
	else
	{
		strncpy(nextpath, path, PATHSIZE - 1);
		strncat(nextpath, "/*", PATHSIZE - 1);

		if(glob(nextpath, 0, NULL, &globres) < 0)
		{
			perror("glob");
			exit(1);
		}
		
		strncpy(nextpath, path, PATHSIZE - 1);
		strncat(nextpath, "/.*", PATHSIZE - 1);

		if(glob(nextpath, GLOB_APPEND, NULL, &globres) < 0)
		{
			perror("glob");
			exit(1);
		}

		sum = statres.st_blocks;//add self
		for(i = 0; i < globres.gl_pathc; i++)
		{
			if(path_noloop(globres.gl_pathv[i]))
			{
				sum += mydu(globres.gl_pathv[i]);
			}
		}

		globfree(&globres);

		return sum;
	}
}

static int path_noloop(const char * path)
{
	char * pos;
	//pos指向最后一个/字符
	pos = strrchr(path, '/');
	if(pos == NULL)
	{
		printf("strrchr error\n");
		exit(1);
	}
	//是 . 或 .. 返回0
	if(strcmp(pos + 1, ".") == 0 || strcmp(pos + 1, "..") == 0)
		return 0;
	//不是 . 或 .. 返回1
	return 1;
}
